import { describe, getPlayer } from '$lib';
import { Size } from '$lib/components';
import { log } from '$lib/log';
import { getPos3, move, onTile } from '$lib/pos3';
import { logVisible } from '$lib/render3';
import { defineComponent, hasComponent, removeEntity } from '$lib/ecs';
import { Evasion, Precision } from './stats';
import { random } from '$lib/random';
import { Hunger } from './hunger';
import { cleanup } from '$lib/cleanup';
import { Clock } from '$lib/clock';
import { Heart } from '$lib/content/heart';

export const Prey = defineComponent('Prey', {});

export const isAttackable = (world, e, ref) => {
  if (ref === getPlayer(world)) {
    // TODO
    return hasComponent(world, Prey, e);
  }
  // TODO
  return false;
};

/**
 * Currently only used to determine if a successful attack will make
 * target consumed where applicable
 */
export const isTiny = (world, e, ref) => {
  if (!hasComponent(world, Size, e) || !hasComponent(world, Size, ref))
    return false;
  return Size.size[e] < Size.size[ref]-1;
};

export const MoleAttackAndConsume = (target) => (world, e) => {
  return {
    error: false,
    action: () => {
      const precision = Precision.amount[e];
      const evasion = Evasion.amount[target];
      const {x, y, z} = getPos3(target);
      const p = getPos3(e);
      move(world, e, x, y, z);
      if (precision*random() > evasion*random()) {
        logVisible(e, `${describe(world, e)} devours ${describe(world, target)}!`);
        // TODO
        Hunger.satiation[e] += 20;
        cleanup(world, target);
        removeEntity(world, target);
      } else {
        logVisible(e, `${describe(world, e)} attacks ${describe(world, target)}, but it slips away!`);
        move(world, target, p.x, p.y, p.z);
      }
      Clock.time[e] += Heart.heartbeat[e];
    },
  };
};
